<?php
namespace app\index\controller;

use app\common\controller\Marcketline;
use app\common\model\coin\CoinList;
use think\Exception;
use app\common\model\coin\CoinUser;
use app\common\model\trade\TradeCoinBuy;
use think\Db;
use app\common\model\trade\TradeCoinSales;
use app\common\controller\Trade;

class Tradecoin extends Base
{
	/**
	 * 获取系统交易对
	 * @return unknown
	 */
	public function getSymbol()
	{
		//获取所有的数字货币
		$coin_list = CoinList::where(['state' => 1])->field('id,name')->select()->toArray();
		//排列组合交易对
		$res = [];
		$tick = new Marcketline();
		foreach ($coin_list as $val) {
			$item_temp = [
					'name' => $val['name'],
					'data' => [],
			];
			foreach ($coin_list as $v) {
				if($val['id'] != $v['id']) {
					$symbole = $v['name'].$val['name'];
					$tick_real = $tick->getSymbolClose(strtolower($symbole));
					if($tick_real){
						$temp_item = [$v,$val,$tick_real];
						$item_temp['data'][] = $temp_item;
					}
				}
			}
			$res[] = $item_temp;
		}
		return jsonSuccess($res);
	}
	
	/**
	 * 获取用户可用金额
	 * @return unknown
	 */
	public function getAvaliblePrice()
	{
		$coin_id = $this->reqeust->post('coin_id');
		$avalible_price = CoinUser::where(['user_id' => $this->user_id,'coin_id' => $coin_id])->value('avalible_price');
		$avalible_price = $avalible_price ? $avalible_price : 0;
		return jsonSuccess($avalible_price);
	}
	
	/**
	 * 买入、卖出委托列表
	 * @return unknown
	 */
	public function getTradeBuy()
	{
		//判断查询方式1、查询正常，2查询全部
		$trade_style = $this->reqeust->post('trade_style');
		try {
			$where = ['user_id' => $this->user_id,'state' => ['neq',0]];
			if($trade_style == 1) {
				$list = TradeCoinBuy::where($where)->order('id desc')->limit(5)->select();
			} else {
				$list = TradeCoinSales::where($where)->order('id desc')->limit(5)->select();
			}
		} catch (Exception $e) {
			return jsonError($e->getMessage());
		}
		return jsonSuccess($list);
	}
	/**
	 * 买入委托
	 * @throws Exception
	 * @return unknown
	 */
	public function buy()
	{
		$this->checkReal($this->user_id);
		$data = $this->reqeust->post('');
		Db::startTrans();
		try {
			//提取客户端穿的数据
			$data['buy_num'] = $data['num'];
			$data['buy_price'] = $data['price'];
			unset($data['num']);
			unset($data['price']);
			//验证数据的合法性
			if(!$data['base_currency'])throw new Exception('非法操作');
			if(!$data['quote_currency'])throw new Exception('非法操作');
			if(!$data['style'])throw new Exception('请选择交易方式');
			if($data['style'] != 2) {
				if(!$data['buy_num'])throw new Exception('请输入数量');
				if(!$data['buy_price'])throw new Exception('请输入价格');
				$data['total_price'] = $data['buy_num'] * $data['buy_price'];
				if($data['style'] == 3){
					if(!$data['touch_price'])throw new Exception('请输入触发价');
					$start_loss = 1.1 * $data['marcket_price'];
					$end_loss = 2 * $data['marcket_price'];
					if($data['buy_price'] > $end_loss || $data['buy_price'] < $start_loss) {
						throw new Exception('止盈止损在10% - 100%之间');
					}
				}
			}
			unset($data['marcket_price']);
			if(!$data['total_price']) throw new Exception('非法操作');
			//重组数据
			$data['surplus_num'] = $data['buy_num'];
			$data['create_time'] = time();
			$data['update_time'] = time();
			$data['user_id'] = $this->user_id;
			//判断数据的正确性
			$base_currency = CoinList::get($data['base_currency']);
			$quote_currency = CoinList::get($data['quote_currency']);
			if(!$base_currency || !$quote_currency)throw new Exception('交易对错误');
			//判断交易对的余额是否充足
			$avalible_price = CoinUser::where(['user_id' => $this->user_id,'coin_id' => $quote_currency->id])->value('avalible_price');
			if(!$avalible_price)throw new Exception('账户余额不足');
			if($avalible_price < $data['total_price'])throw new Exception("{$quote_currency->name}余额不足");
			//设置交易对
			$data['trans_pair'] = strtolower($base_currency->name.$quote_currency->name);
			//改变用户账户金额
			CoinUser::where(['user_id' => $this->user_id,'coin_id' => $quote_currency->id])->setDec('avalible_price',$data['total_price']);
			CoinUser::where(['user_id' => $this->user_id,'coin_id' => $quote_currency->id])->setInc('freezing_price',$data['total_price']);
			//添加买入委托
			$buy = TradeCoinBuy::create($data);
			//执行委托操作
			$trade_mate = new Trade();
			call_user_func_array([$trade_mate,'buyMate'], [$buy->id,$this->user_id]);
			Db::commit();
		} catch (Exception $e) {
			Db::rollback();
			return jsonError($e->getMessage());
		}
		return jsonSuccess('买入成功');
	}
	
	/**
	 * 币币卖出委托
	 * @throws Exception
	 * @return unknown
	 */
	public function sale()
	{
		$data = $this->reqeust->post('');
		Db::startTrans();
		try {
			//提取客户端穿的数据
			$data['sale_num'] = $data['num'];
			$data['sale_price'] = $data['price'];
			unset($data['num']);
			unset($data['price']);
			//验证数据的合法性
			if(!$data['base_currency'])throw new Exception('非法操作');
			if(!$data['quote_currency'])throw new Exception('非法操作');
			if(!$data['style'])throw new Exception('请选择交易方式');
			if($data['style'] != 2) {
				if(!$data['sale_num'])throw new Exception('请输入数量');
				if(!$data['sale_price'])throw new Exception('请输入价格');
				$data['total_price'] = $data['sale_num'] * $data['sale_price'];
				if($data['style'] == 3){
					if(!$data['touch_price'])throw new Exception('请输入触发价');
					$start_loss = 1.1 * $data['marcket_price'];
					$end_loss = 2 * $data['marcket_price'];
					if($data['sale_price'] > $end_loss || $data['sale_price'] < $start_loss) {
						throw new Exception('止盈止损在10% - 100%之间');
					}
				}
			}
			unset($data['marcket_price']);
			if(!$data['total_price']) throw new Exception('非法操作');
			//重组数据
			$data['surplus_num'] = $data['sale_num'];
			$data['create_time'] = time();
			$data['update_time'] = time();
			$data['user_id'] = $this->user_id;
			//判断数据的正确性
			$base_currency = CoinList::get($data['base_currency']);
			$quote_currency = CoinList::get($data['quote_currency']);
			if(!$base_currency || !$quote_currency)throw new Exception('交易对错误');
			//判断交易对的余额是否充足
			$avalible_price = CoinUser::where(['user_id' => $this->user_id,'coin_id' => $base_currency->id])->value('avalible_price');
			if(!$avalible_price)throw new Exception('账户余额不足');
			if($avalible_price < $data['sale_num'])throw new Exception("{$base_currency->name}余额不足");
			//设置交易对
			$data['trans_pair'] = strtolower($base_currency->name.$quote_currency->name);
			//改变用户账户金额
			CoinUser::where(['user_id' => $this->user_id,'coin_id' => $base_currency->id])->setDec('avalible_price',$data['sale_num']);
			CoinUser::where(['user_id' => $this->user_id,'coin_id' => $base_currency->id])->setInc('freezing_price',$data['sale_num']);
			//添加卖出委托
			$sale = TradeCoinSales::create($data);
			//执行委托操作
			$trade_mate = new Trade();
			call_user_func_array([$trade_mate,'saleMate'], [$sale->id,$this->user_id]);
			Db::commit();
		} catch (Exception $e) {
			Db::rollback();
			return jsonError($e->getMessage());
		}
		return jsonSuccess('卖出成功');
	}
	
	/**
	 * 撤销订单
	 * @return unknown
	 */
	public function cancelTrade()
	{
		$data = $this->request->post('');
		Db::startTrans();
		try {
			if($data['trade_style'] == 1) {
				//撤销买入订单
				$trade_buy = TradeCoinBuy::get($data['id']);
				//改变用户账户金额
				CoinUser::where(['user_id' => $this->user_id,'coin_id' => $trade_buy->quote_currency])->setInc('avalible_price',$trade_buy->surplus_num);
				CoinUser::where(['user_id' => $this->user_id,'coin_id' => $trade_buy->quote_currency])->setDec('freezing_price',$trade_buy->surplus_num);
				//改变状态
				$trade_buy->save(['state' => 0,'update_time' => time()]);
			} elseif ($data['trade_style'] == 2) {
				$trade_sale = TradeCoinSales::get($data['id']);
				//改变用户账户金额
				CoinUser::where(['user_id' => $this->user_id,'coin_id' => $trade_sale->base_currency])->setInc('avalible_price',$trade_sale->surplus_num);
				CoinUser::where(['user_id' => $this->user_id,'coin_id' => $trade_sale->base_currency])->setDec('freezing_price',$trade_sale->surplus_num);
				//改变状态
				$trade_sale->save(['state' => 0,'update_time' => time()]);
			}
			Db::commit();
		} catch (Exception $e) {
			Db::rollback();
			return jsonError($e->getMessage());
		}
		return jsonSuccess('撤销成功');
	}
	
	/**
	 * 币币交易列表
	 * @return unknown
	 */
	public function getTradeList()
	{
		$trade_style = $this->request->post('trade_style');
		$where = ['user_id' => $this->user_id];
		if($trade_style) {
			//卖出委托
			$list = TradeCoinSales::where($where)->order('id desc')->paginate();
		} else {
			//买入委托
			$list = TradeCoinBuy::where($where)->order('id desc')->paginate();
		}
		return jsonSuccess($list);
	}
}